package net.ikenway.springboot.demo.Utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author MasterKenway <zk@ikenway.net>
 * @Description
 * @date Created Date 12/13/2020
 */
@Component
public class JwtTokenUtil implements Serializable {
    @Value("${jwt.token.expiration-time}")
    private Long expirationTime;

    @Value("${jwt.token.client-id}")
    private String clientId;

    @Value("${jwt.token.secret}")
    private String secret;

    public String generateToken(UserDetails userDetails) {
        Map<String, Object> claims = new HashMap<>(16);
        claims.put("sub", userDetails.getUsername());
        return Jwts.builder()
                .setClaims(claims)
                .setIssuer(this.clientId)
                .setId(UUID.randomUUID().toString())
                .setExpiration(new Date(Instant.now().toEpochMilli() + this.expirationTime))
                .signWith(Keys.hmacShaKeyFor(this.secret.getBytes(StandardCharsets.UTF_8)))
                .compact();
    }

    public Boolean validateToken(String token, UserDetails userDetails) throws ExpiredJwtException {
        if (token == null) return false;
        return getClaimsFromToken(token).getSubject().equals(userDetails.getUsername()) && !isTokenExpired(token);
    }

    public Boolean isTokenExpired(String token) throws ExpiredJwtException {
        return getClaimsFromToken(token).getExpiration().before(new Date());
    }

    public String getUsernameFromToken(String token) throws ExpiredJwtException, JwtException {
        if (token.isEmpty()) throw new JwtException("");
        return getClaimsFromToken(token).getSubject();
    }

    public Claims getClaimsFromToken(String token) throws ExpiredJwtException, JwtException {
        if (token.isEmpty()) throw new JwtException("");
        return Jwts.parserBuilder()
                .setSigningKey(Keys.hmacShaKeyFor(this.secret.getBytes(StandardCharsets.UTF_8)))
                .build().parseClaimsJws(token)
                .getBody();
    }

}
